<?php declare(strict_types=1);

namespace shali\ydb\think2fa\controller;

use app\BaseController;
use app\common\model\agent\Agent;
use app\common\utils\ResponseUtils;
use Exception;
use shali\ydb\think2fa\model\Agent2Fa;
use shali\ydb\think2fa\service\Agent2FaService;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\View;
use think\Request;
use think\response\Json;

class Admin extends BaseController
{
    protected function initialize()
    {
        parent::initialize();
        // 配置模版路径
        $this->app->view->config([
            'view_path' => __DIR__ . '/../view/',
        ]);
    }

    /**
     * 两步验证介绍页面
     * @return string
     * @throws Exception
     */
    public function index()
    {
        View::assign([
            'platform' => config('app.app_name'),
            'expired' => date('Y-m-d', strtotime('+7 days')),
        ]);
        return View::fetch('admin/index');
    }

    /**
     * 获取登录者两步验证开启状态
     * @param Request $request
     * @return Json
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function status(Request $request): Json
    {
        $agent = Agent::field(['agent_no'])->find($request->userInfo->id);
        return ResponseUtils::success([
            'status' => Agent2Fa::findByAgentNo($agent->agent_no)->status ?? Agent2Fa::STATUS_DISABLE,
        ]);
    }

    /**
     * 开启、关闭两步验证
     * @param Request $request
     * @return Json
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function updateStatus(Request $request): Json
    {
        $params = $request->param();
        $this->validate($params, ['status' => 'require|in:0,1',], ['status.in' => '状态值错误']);
        $agent = Agent::field(['id', 'agent_no', 'mobile'])->find($request->userInfo->id);
        $errMsg = Agent2FaService::updateStatus($agent, intval($params['status']));
        if (!is_null($errMsg)) {
            return ResponseUtils::error($errMsg);
        }
        return ResponseUtils::success('更新成功');
    }

    /**
     * 获得两步验证码
     * @param Request $request
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function qrCode(Request $request): Json
    {
        $agent = Agent::field(['id', 'agent_no', 'mobile'])->find($request->userInfo->id);
        $qrCode = Agent2FaService::getQrCode($agent);
        if (is_null($qrCode)) {
            return ResponseUtils::error('您还未开启两步验证，请先开启两步验证');
        }
        return ResponseUtils::success([
            'qrCode' => $qrCode,
        ]);
    }

    /**
     * 重置两步验证码密钥
     * @param Request $request
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function resetSecret(Request $request): Json
    {
        $agent = Agent::field(['id', 'agent_no', 'mobile'])->find($request->userInfo->id);
        $errMsg = Agent2FaService::resetSecret($agent);
        if (!is_null($errMsg)) {
            return ResponseUtils::error($errMsg);
        }
        return ResponseUtils::success([
            'qrCode' => Agent2FaService::getQrCode($agent),
        ]);
    }

    /**
     * 临时验证代理验证码
     * @param Request $request
     * @return Json
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function verify(Request $request): Json
    {
        $params = $request->param();
        $this->validate(
            $params,
            [
                'code' => 'require|number|length:6',
            ],
            [
                'code.length' => '验证码长度为6位',
            ]
        );
        $agentId = empty($params['agentId']) ? $request->userInfo->id : $params['agentId'];
        $agent = Agent::field(['id', 'agent_no', 'mobile'])->find($agentId);
        if (is_null($agent)) {
            return ResponseUtils::error('用户不存在');
        }
        $errMsg = Agent2FaService::verifyCode($agent, $params['code']);
        if (!is_null($errMsg)) {
            return ResponseUtils::error($errMsg);
        }
        return ResponseUtils::success('验证成功');
    }
}